#include "udpserver.hpp"
#include <unordered_set>

std::unordered_set<string> blockcmd = {"rm","mv","cp"};     //过滤掉不安全的指令！

//让服务器绑定的端口号可动态调整：./udpserver port
void Usage(char* s)
{
    cout << "Usage of " << s << ": " << string(s) + " + port" << endl; 
}

string messageEcho(const string& msg)
{
    cout << "server#: " << msg << endl;
    return msg;
}

bool isCommandSafe(const string& cmd)
{
    if(blockcmd.find(cmd) != blockcmd.end())
        return false;
    return true;
}

string excuteCommand(const string& cmd)
{
    //1.保证命令的安全性
    if(!isCommandSafe(cmd))
        return "your command is not safe";

    //2.获取命令 --> 把文件缓冲区中的内容依次读出后返回！
    FILE* fp = popen(cmd.c_str(),"r");
    string res;
    char buffer[1024];
    while(fgets(buffer,sizeof(buffer),fp))
    {
        res += buffer;
    }
    fclose(fp);
    return res;
}

int main(int argc, char* argv[])
{
    if(argc < 2)
    {
        Usage(argv[0]);
    }
    else
    {
        int port = stoi(argv[1]);
        UdpServer ser(port);
        ser.Init();
        //ser.Run(excuteCommand);
        //ser.Run(messageEcho);
        ser.BroadCast();
    }
    return 0;
}